package com.sjb.mianshiya.aspect;

import com.sjb.mianshiya.annotation.DistributedLock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author:sjb
 * @CreateTime:2024-11-18
 * @Description: 锁切面
 * @Version：1.0
 */
@Aspect
@Component
public class DistributedLockAspect {

    @Resource
    private RedissonClient redissonClient;

    @Around("@annotation(distributedLock)")
    public Object around(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Exception {

        String key = distributedLock.key();
        TimeUnit timeUnit = distributedLock.timeUnit();
        long easeTime = distributedLock.easeTime();
        long waitTime = distributedLock.waitTime();

        RLock lock = redissonClient.getLock(key);

        boolean acquired = false;

        try {
            acquired = lock.tryLock(waitTime, easeTime, timeUnit);
            if (acquired) {
                // 获取锁成功 执行目标方法
                return joinPoint.proceed();
            } else {
                // 获取锁失败 抛出异常处理
                throw new RuntimeException("Could not acquire lock: " + key);
            }
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            if (acquired) {
                lock.unlock();
            }
        }
    }
}
